﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace ColorApplication
{
    public partial class DownloadPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["Filename"] != null)
                {
                    if (Session["Filename"].ToString() != string.Empty)
                    {
                        string filename = Session["Filename"].ToString();
                        // Download .csv file
                        if (File.Exists(Server.MapPath("~/CApplication/") + filename))
                        {
                            // Set Sesion Null 
                            Session["filename"] = null;
                            // Read Binary Data
                            byte[] Filedata = File.ReadAllBytes(Server.MapPath("~/CApplication/") + filename);
                            // Delete file after read data
                            File.Delete(Server.MapPath("~/CApplication/") + filename);
                            DownLoadCSV(filename, Filedata);
                           
                        }
                    }
                 }
               
            }
            catch (Exception err)
            {
                //Response.Redirect("~/");
            }
        }


        protected void DownLoadCSV(string filename, byte[] Filedata)
        {
            // This is file download code for .csv file
            string attachment = "attachment; filename=" + filename;
            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "text/csv";
            Response.AddHeader("Pragma", "public");
            // Write Binay Data to response
            Response.BinaryWrite(Filedata);
            Response.End();
        }
    }
}